const encrypt = require('./encrypt')

const decrypt = (str) => encrypt.decrypt(str);

const updateUsername = ({ findData, updateOne, encrypt }) => (req, res) => {
    let data = '';
    req.on('data', (chunk) => data += chunk);
    req.on('end', async () => {
        const { password, newUsername } = JSON.parse(data);
        const { username: oldUsername } = req.userInfo;
        //验证密码正确性
        const [user] = await findData({ collection: 'userProfile', find: { username: oldUsername } })
        console.log("user:", user);
        if (user && user.password === decrypt(password)) {
            const lastUpdate = Date.now();
            const { _id, role } = user;
            //改用户名 更新时间 
            const result = await updateOne({ collection: "userProfile", _id, data: { username: newUsername, lastUpdate } });
            if (result) {
                //生成新的 jwt
                const newUser = { _id, role, username: newUsername, lastUpdate };
                const jwt = encrypt(newUser);
                return res.json({ message: '修改成功' + newUsername, jwt, newUser });
            }

        }
        res.status(500).json({ message: '修改失败' });
    });
}

const updatePassword = ({ findData, updateOne, encrypt }) => (req, res) => {
    let data = '';
    req.on('data', (chunk) => data += chunk);
    req.on('end', async () => {
        const { password, newPassword } = JSON.parse(data);
        const { username } = req.userInfo;
        const payload = { status: 500, message: '修改失败' };
        //验证密码正确性
        const [user] = await findData({ collection: 'userProfile', find: { username } });
        console.log("user:", user);
        if (user) {
            if (user.password === decrypt(password)) {
                //改密码 & 更新时间
                const lastUpdate = Date.now();
                const result = await updateOne({ collection: "userProfile", _id: user._id, data: { password: decrypt(newPassword), lastUpdate } });
                if (result) {
                    //返回 加入新lastUpdate的jwt
                    const { password, ...auth } = user;
                    const newUser = { ...auth, lastUpdate };
                    const jwt = encrypt(newUser);
                    payload.status = 200;
                    payload.message = '修改成功';
                    payload.jwt = jwt;
                    payload.newUser = newUser;
                };
            } else payload.message = '密码错误';
        }
        const { status, ...body } = payload;
        res.status(status).json(body);
    });
}

module.exports = { updateUsername, updatePassword };

